package net.javastone.toolkit.robot.dingding.service;

import net.javastone.toolkit.robot.dingding.config.AppProperties;
import net.javastone.toolkit.robot.dingding.model.DingDingRequest;
import net.javastone.toolkit.robot.dingding.model.DingDingResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * Created by sdliang on 2018/11/6.
 */
@Service
public class DingDingServiceImpl implements DingDingService {

  @Autowired
  private AppProperties appProperties;

  @Autowired
  private RestTemplate restTemplate;

  @Override
  public DingDingResponse gitlabWiki(String accessToken, DingDingRequest request) {
    try {
      DingDingResponse response = restTemplate
          .postForObject(getWikiURI(accessToken), request, DingDingResponse.class);
      return response;
    } catch (RestClientException e) {
      throw new RuntimeException("call dingding service error: " + e.getMessage(), e);
    }
  }

  /**
   * 获取钉钉通知的URL
   *
   * @param accessToken
   * @return
   */
  private String getWikiURI(String accessToken) {
    return String.format(appProperties.getWebhookWikiDingding(), accessToken);
  }

}
